package com.gm.commonlib.base.baseui.baseListviewUI;

import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.gm.commonlib.application.MyApplicationHolder;
import com.gm.commonlib.base.baseBean.BaseListResp;
import com.gm.commonlib.base.baseBean.BasePageData;
import com.gm.commonlib.base.baseBean.BaseResp;
import com.gm.commonlib.base.baseBean.PageInfo;
import com.gm.commonlib.base.baseui.baseFragment.BaseFragment;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.network.HttpClient;
import com.gm.commonlib.network.HttpResultCode;
import com.gm.commonlib.network.HttpServicesHolder;
import java.util.ArrayList;
import java.util.List;


public abstract class BasePullToRefeshFragment<
       DataType,
       NetworkResponse>
       extends BaseFragment {

   protected PageInfo mPageInfo = null;
   protected List<DataType> mDatas = new ArrayList<>();
   protected boolean mIsGetData;
   protected BaseAdapter mBaseAdapter = null;

   public   long mCurrentPage=1;

    @Override
    protected void onPostCreateContentView(ViewGroup viewGroup, Bundle savedInstanceState) {
        initPullToRefreshListView();
    }

    public void setIsGetData(boolean mIsGetData) {
        this.mIsGetData = mIsGetData;
    }

    /**
    * 创建界面Item的适配器
    *
    * @return 适配器
    */
   protected abstract BaseAdapter createTempBaseAdapter();



   protected void notifyListDataSetChanged() {
       if (mBaseAdapter != null) {
           mBaseAdapter.notifyDataSetChanged();
       }

   }



   public void  initPullToRefreshListView(){

   }



   @Override
   public void onActivityCreated(Bundle savedInstanceState) {
       super.onActivityCreated(savedInstanceState);
       if (mIsGetData) {
           refreshData();
           mIsGetData = false;
       }
   }

   @Override
   public void onResume() {
       super.onResume();
       if (mIsGetData) {
           refreshData();
           mIsGetData = false;
       }
   }

   public void refreshData() {

       onRefreshView();
   }



   protected void requestPageData(long index, boolean fresh) {
       mCurrentPage=index;
       isRefresh = fresh;
     //  LoadingDialog.show(getContext());
       HttpClient.sendRequest(null, fresh, getHttpServicesHolder(index), new BaseHttpObserver<NetworkResponse>() {
           @Override
           public void onCompleted() {
               super.onCompleted();

               getDataOnCompleted();
               hidLoadingDialog();
           }

           @Override
           public void onNext(NetworkResponse resp) {
               BaseResp baseResp=((BaseResp) resp);
               if (baseResp.getCode()== HttpResultCode.TOKEN_ERROR.getCode()
                       || baseResp.getCode()==HttpResultCode.OTHER_LOGIN.getCode()){
                   MyApplicationHolder.getApplication().login(baseResp.getCode());
               }
               else {
                   onHandleResult(resp, isRefresh);
               }

           }

           @Override
           protected void onError(String error) {
               showError(error);

           }
       }, false);
   }

   public  void  getDataOnCompleted(){
       if (mPageInfo!=null){
           if (isLastPagerData(mPageInfo) || mDatas.isEmpty()) {
               setRefreshAndLoadEnable(true,false);
           } else {
               setRefreshAndLoadEnable(true,true);
           }
       }
       else {
           setRefreshAndLoadEnable(true,false);
       }

   }



   protected void showError(String error) {
      showToast(error);
   }

   /**
    * 获取HttpServicesHolder，将其放入子类实现，以方便各种不同的网络请求
    *
    * @param index
    * @return
    */
   protected abstract HttpServicesHolder<?, NetworkResponse> getHttpServicesHolder(long index);

   protected void onHandleResult(NetworkResponse resp, boolean isRefresh) {
       if (resp instanceof BaseListResp) {
           handleListResponse((BaseListResp<DataType>) resp,isRefresh);
       }
       if (resp instanceof BasePageData){
           handlePageResponse((BasePageData<DataType>) resp,isRefresh);
       }

   }


   protected void handleListResponse(BaseListResp<DataType> resp, boolean isRefresh) {
        int code = resp.getCode();
        if (HttpResultCode.REQUEST_SUCCESS.getCode()==code) {
            if (isRefresh) {
                mDatas.clear();
            }
            renderListResponse(mDatas, resp);
            getDataFinish(mDatas);
            notifyListDataSetChanged();
        } else {
            onHttpError((NetworkResponse) resp);
        }

    }

    protected void handlePageResponse(BasePageData<DataType> resp, boolean isRefresh) {
        int code = resp.getCode();
        if (HttpResultCode.REQUEST_SUCCESS.getCode()==code) {
            if (isRefresh) {
                mDatas.clear();
            }
            if (resp.getData()!=null){
                mPageInfo=resp.getData().getPageInfo();
                if (resp.getData().getDatas()!=null){
                    mDatas.addAll(resp.getData().getDatas());
                }

            }
            getDataFinish(mDatas);
            notifyListDataSetChanged();
        } else {
            onHttpError((NetworkResponse) resp);
        }

    }


    protected void renderDataRespResponse(List<DataType> mDatas, BaseListResp<DataType> resps) {
        if (resps.getDatas() != null) {
            mDatas.addAll(resps.getDatas());
        }
    }

   protected void renderListResponse(List<DataType> mDatas, BaseListResp<DataType> resps) {
       if (resps.getDatas() != null && !resps.getDatas().isEmpty()) {
           mDatas.addAll(resps.getDatas());
       }
   }




   protected void getDataFinish(List<DataType> mDatas) {

   }

   protected void setRefreshAndLoadEnable(boolean isPull,boolean isLoadMore) {

   }

   protected boolean isLastPagerData(PageInfo pageInfo) {
       return pageInfo != null && pageInfo.getTotalPages() > 0 && (mCurrentPage ==
               pageInfo.getTotalPages());
   }


   boolean isRefresh = false;

   public boolean isRefresh() {
       return isRefresh;
   }


   protected void onHttpError(NetworkResponse resp) {
       showError(resp);
   }

   protected void showError(NetworkResponse resp) {
       if (resp instanceof BaseResp) {
           String errorMsg = ((BaseResp) resp).getMessage();
           showError(errorMsg);
       } else {
           showError("网络异常");
       }

   }

   public void requestPageData(long index) {
       requestPageData(index, true);
   }


   protected long buildPageIndex(boolean isFirstPage, PageInfo pageInfo) {
       if (pageInfo==null){
           return 1;
       }
       if (isFirstPage) {
           return 1;
       } else if (pageInfo != null) {
           return mCurrentPage + 1;
       } else {
           return 1;
       }
   }

   public void onRefreshView() {
       isRefresh(true);
       requestPageData(buildPageIndex(true, null));
   }

   public void onRefresh(){
       onRefreshView();
   }

   protected void isRefresh(boolean isFresh) {
   }


   /**
    * 提供默认的内容为空的处理</br>
    * 服务端提示，内容为空</br>
    *
    * @param mDatas    要刷新的数据
    * @param isRefresh 刷新标志 如果为true时，会清空缓存，然后刷新，false时不会清空之前的缓存
    */
   protected void renderEmptyResultDatas(List<DataType> mDatas, boolean isRefresh) {
       if (isRefresh) {
           mDatas.clear();
       }
   }


   /**
    * 提供默认的创建刷新界面的处理</br>
    *
    * @param parent 向parent设置滑动布局 内容
    */
   protected void onCreateContentBody(ViewGroup parent) {


   }





}
